Algorithm to find Determinant of a Matrix¶
The idea is to first convert the given matrix to echelon form and then take the product of the diagonal elements
In [1]:
def det(mat):
if len(mat) != len(mat[0]):
raise ArithmeticError("Parameter must be a square matrix")
if len(mat) == 1:
return mat[0]
if len(mat) == 2:
return mat[0][0]*mat[1][1]-mat[0][1]*mat[1][0]
factor = 1.0
# copying the contents of matrix in a seperate array
x = [row[:] for row in mat]
while len(x)>2:
# in case the first element of the matrix is 0
# we swap the row with another row whose first element is not 0
if x[0][0] == 0.0:
for i in range(len(x)):
# if we find such a row, we swap it with the first row and the factor becomes -1
if x[i][0] != 0:
for j in range(len(x)):
temp = x[i][j]
x[i][j] = x[0][j]
x[0][j] = temp
factor *= -1.0
break
# if we reach the end of the matrix and still don't find a suitable row, we return 0
if x[i][0] == 0 and i==len(x)-1:
return 0
factor *= x[0][0]
arr = []
for i in range(1,len(x)):
tempArr = []
for j in range(1,len(x)):
tempArr.append(x[i][j]-x[0][j]*x[i][0]/x[0][0])
arr.append(tempArr[:])
x = [row[:] for row in arr]
# at the end of the loop the size of x is always 2, so we can directly compute the result
return factor*(x[0][0]*x[1][1]-x[0][1]*x[1][0])
These are the matrices on which we will test the algorithm¶
In [2]:
mat1 = [
[2.0,5.0,1.0],
[0.0,3.0,2.0],
[0.0,0.0,4.0]
]
mat2 = [
[5.0,2.0,3.0,1.0],
[7.0,6.0,4.0,2.0],
[5.0,6.0,7.0,5.0],
[5.0,7.0,9.0,7.0]
]
Driver Code¶
In [3]:
if __name__ == "__main__":
print(det(mat1))
print(det(mat2))
24.0 16.0
Now we'll check if our calculations are correct, using numpy¶
In [4]:
import numpy as np
# converting into numpy array
nmat1 = np.array(mat1)
nmat2 = np.array(mat2)
# computing determinant
det1 = np.linalg.det(nmat1)
det2 = np.linalg.det(nmat2)
print(det1,det2)
23.999999999999993 15.999999999999913